package com.jinyijia.admin.interfaces;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinyijia.admin.config.Constant;
import com.jinyijia.admin.interfaces.dto.BrandSaveDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestOperations;

import java.util.Objects;

/**
 * Created by yangrd on 2018/3/11
 **/
@RestController
@RequestMapping(Constant.Path.BRANDS)
public class BrandController {

    @Autowired
    private RestOperations restOperations;

    @Value("${jinYiJia.api.brands}")
    private String apiPath;

    @GetMapping
    public ResponseEntity findAll() {
        return restOperations.getForEntity(apiPath, JSONArray.class);
    }

    @PostMapping
    public ResponseEntity addBrand(@RequestBody BrandSaveDTO dto) {
        StringBuffer url = new StringBuffer(apiPath);
        if (Objects.nonNull(dto.getName())) {
            url.append("?name=").append(dto.getName());
        }
        JSONObject object = restOperations.postForEntity(url.toString(), null, JSONObject.class).getBody();
        return ResponseEntity.ok(object);
    }

    @PutMapping
    public ResponseEntity editBrand(@RequestBody BrandSaveDTO dto) {
        StringBuffer url = new StringBuffer(apiPath).append("/" + dto.getId());
        if (Objects.nonNull(dto.getName())) {
            url.append("?name=").append(dto.getName());
        }
        restOperations.put(url.toString(), null);
        return ResponseEntity.ok("ok");
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deleteBrand(@PathVariable Integer id) {
        StringBuffer url = new StringBuffer(apiPath).append("/" + id);
        restOperations.delete(url.toString());
        return ResponseEntity.ok("ok");
    }
}
